import { createRouter, createWebHashHistory } from 'vue-router'
import Home from '../views/home/home'
import { get } from '@/utils/localStorage'

const routes = [
  // 首页
  {
    path: '/',
    name: 'home',
    component: Home
  },
  // 购物车
  {
    path: '/detail/:id',
    name: 'detail',
    component: () => import(/* webpackChunkName: "detail" */ '../views/detail/detail')
  },
  // 购物车
  {
    path: '/cart',
    name: 'cart',
    component: () => import(/* webpackChunkName: "cart" */ '../views/cart/cart')
  },
  // 订单
  {
    path: '/order',
    name: 'order',
    component: () => import(/* webpackChunkName: "order" */ '../views/order/order')
  },
  // 确认订单
  {
    path: '/confirm',
    name: 'confirm',
    component: () => import(/* webpackChunkName: "confirm" */ '../views/confirm/confirm')
  },
  // 我的
  {
    path: '/personal',
    name: 'personal',
    component: () => import(/* webpackChunkName: "personal" */ '../views/personal/personal')
  },
  // 地址管理
  {
    path: '/address',
    name: 'address',
    component: () => import(/* webpackChunkName: "address" */ '../views/address/address')
  },
  // 新建地址
  {
    path: '/createAddress',
    name: 'createAddress',
    component: () => import(/* webpackChunkName: "createAddress" */ '../views/address/createAddress'),
    // 处理收货地址跳转逻辑
    beforeEnter: (to, from, next) => {
      if (localStorage.forCreate === 'true') next();
      else next({ name: 'personal' })
    }
  },
  // 编辑地址
  {
    path: '/editAddress/:id',
    name: 'editAddress',
    component: () => import(/* webpackChunkName: "editAddress" */ '../views/address/editAddress'),
    // 处理收货地址跳转逻辑
    beforeEnter: (to, from, next) => {
      if (localStorage.forEdit === 'true') next();
      else next({ name: 'personal' })
    }
  },
  // 登录 ---- 如果登录了就不显示，跳转到首页
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "login" */ '../views/login/login'),
    beforeEnter: (to, from, next) => {
      const { isLogin } = get('user');
      if (isLogin) next({ name: 'home' })
      else next();
    }
  },
  // 注册 ---- 如果有账户就不显示，跳转到登录界面，如果有登录状态，就跳转到首页
  {
    path: '/register',
    name: 'register',
    component: () => import(/* webpackChunkName: "register" */ '../views/register/register'),
    beforeEnter: (to, from, next) => {
      const { isLogin } = get('user');
      const username = localStorage.username;
      if (isLogin) next({ name: 'home' })
      else if (username) next({ name: 'login' })
      else next()
    }
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  const { isLogin } = get('user');
  if (isLogin || to.name === 'login' || to.name === 'register') next()
  else next({ name: 'login' })
  // 处理收货地址跳转逻辑
  if (to.name !== 'editAddress') localStorage.forEdit = false;
  if (to.name !== 'createAddress') localStorage.forCreate = false;
})

export default router
